/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa165.machineryrental.restclient;

import cz.muni.fi.pa165.machineryrental.dto.MachineDTO;
import cz.muni.fi.pa165.machineryrental.restclient.dialogs.MachineDialog;
import cz.muni.fi.pa165.machineryrental.restclient.dialogs.MachineSearchByDialog;
import cz.muni.fi.pa165.machineryrental.restclient.enums.MachineSearchType;
import cz.muni.fi.pa165.machineryrental.restclient.services.MachineRestService;
import cz.muni.fi.pa165.machineryrental.restclient.services.MachineRestServiceImpl;
import cz.muni.fi.pa165.machineryrental.restclient.utils.Utils;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author huzvak
 */
public class MachinesManipulationPanel extends javax.swing.JPanel {

    private List<MachineDTO> active;

    /**
     * Creates new form MachinesManipulationPanel
     */
    public MachinesManipulationPanel() {

        initComponents();

        this.active = new ArrayList<MachineDTO>();

        // Creates listener, if has been changed any selected row in table
        this.machinesTable.getSelectionModel().addListSelectionListener(
                new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                recomputeCanClick();
            }
        });

        this.recomputeCanClick();
        
    }

    /**
     * Enables/disabled remove button or update button if is any row selected or
     * not.
     */
    private void recomputeCanClick() {

        int selectedRowIndex = this.machinesTable.getSelectedRow();
        System.out.println("Selected row index: " + selectedRowIndex);

        boolean isSelected = selectedRowIndex >= 0;
        this.deleteBtn.setEnabled(isSelected);
        this.updateBtn.setEnabled(isSelected);
    }

    /**
     * Sets data to table
     *
     * @param machines
     */
    private void setToTable(List<LinkedHashMap> machines) {

        if (machines == null) {
            return;
        }

        System.out.println("Count: " + machines.size());
        this.active.clear();

        this.recomputeCanClick();

        Utils.clearTable(this.machinesTable);


        for (LinkedHashMap mach : machines) {

            MachineDTO m;
            try {
                m = Utils.toDtos(mach);
            } catch (ParseException ex) {
                continue;
            }

            this.active.add(m);
            this.addRow(m);
        }
    }

    private void addRow(MachineDTO m) {
        DefaultTableModel model = (DefaultTableModel) this.machinesTable.getModel();
        model.addRow(Utils.toRow(m));
    }

    /**
     * Refreshes data in table
     */
    public void refresh() {

        new SwingWorker<List<LinkedHashMap>, Void>() {
            @Override
            protected List<LinkedHashMap> doInBackground() {

                try {
                    MachineRestService machineService = new MachineRestServiceImpl();
                    return (List<LinkedHashMap>) machineService.findAll();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                }

                return null;
            }

            @Override
            protected void done() {
                try {
                    List<LinkedHashMap> machines = this.get();
                    setToTable(machines);

                } catch (InterruptedException ex) {
                    Logger.getLogger(MachinesManipulationPanel.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ExecutionException ex) {
                    Logger.getLogger(MachinesManipulationPanel.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        }.execute();
    }

    private void removeActiveRow() {
        if (this.machinesTable.getSelectedRow() < 0) {
            JOptionPane.showMessageDialog(null, "Select any row and repeat operation.", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        final MachineDTO toRemove = this.active.get(this.machinesTable.getSelectedRow());
        int result = JOptionPane.showConfirmDialog(null, "Are you sure you want to remove machine " + toRemove, "Remove?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (result == 1) { //No
            return;
        }

        new SwingWorker<Void, Void>() {
            @Override
            protected Void doInBackground() {

                try {
                    MachineRestService service = new MachineRestServiceImpl();
                    service.remove(toRemove.getId());
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                }

                return null;
            }

            @Override
            protected void done() {
                refresh();
            }
        }.execute();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        toolbar = new javax.swing.JToolBar();
        refreshBtn = new javax.swing.JButton();
        createBtn = new javax.swing.JButton();
        updateBtn = new javax.swing.JButton();
        deleteBtn = new javax.swing.JButton();
        searchBtn = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        machinesTable = new javax.swing.JTable();

        setLayout(new java.awt.BorderLayout());

        toolbar.setRollover(true);

        refreshBtn.setText("Refresh");
        refreshBtn.setFocusable(false);
        refreshBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        refreshBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        refreshBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                refreshBtnMouseClicked(evt);
            }
        });
        toolbar.add(refreshBtn);

        createBtn.setText("Create Machine");
        createBtn.setFocusable(false);
        createBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        createBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        createBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                createBtnMouseClicked(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                createBtnMouseReleased(evt);
            }
        });
        toolbar.add(createBtn);
        createBtn.getAccessibleContext().setAccessibleName("createBtn");

        updateBtn.setText("Update machine");
        updateBtn.setFocusable(false);
        updateBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        updateBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        updateBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                updateBtnMouseClicked(evt);
            }
        });
        toolbar.add(updateBtn);

        deleteBtn.setText("Delete machine");
        deleteBtn.setFocusable(false);
        deleteBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        deleteBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        deleteBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                deleteBtnMouseClicked(evt);
            }
        });
        toolbar.add(deleteBtn);

        searchBtn.setText("Search");
        searchBtn.setFocusable(false);
        searchBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        searchBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        searchBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                searchBtnMouseClicked(evt);
            }
        });
        toolbar.add(searchBtn);

        add(toolbar, java.awt.BorderLayout.PAGE_START);

        machinesTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Brand", "Model", "Code", "Year"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        machinesTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(machinesTable);
        machinesTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        add(jScrollPane1, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    private void createImpl() {
        final MachineDTO added = new MachineDTO();

        MachineDialog md = new MachineDialog(new JFrame(), true, added, true);
        md.setVisible(true);

        if (md.getDialogResult()) {

            new SwingWorker<Void, Void>() {
                @Override
                protected Void doInBackground() {

                    try {
                        MachineRestService service = new MachineRestServiceImpl();
                        service.create(added);
                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                    }

                    return null;
                }

                @Override
                protected void done() {
                    refresh();
                }
            }.execute();
        }
    }
    
    private void createBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_createBtnMouseClicked
        this.createImpl();
        
    }//GEN-LAST:event_createBtnMouseClicked

    private void updateBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_updateBtnMouseClicked

        final MachineDTO toEdit = this.active.get(this.machinesTable.getSelectedRow());

        MachineDialog md = new MachineDialog(new JFrame(), true, toEdit, false);
        md.setVisible(true);

        if (md.getDialogResult()) {

            new SwingWorker<Void, Void>() {
                @Override
                protected Void doInBackground() {

                    try {

                        MachineRestService service = new MachineRestServiceImpl();
                        service.update(toEdit);
                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                    }

                    return null;
                }

                @Override
                protected void done() {
                    refresh();
                }
            }.execute();
        }

    }//GEN-LAST:event_updateBtnMouseClicked

    private void deleteBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_deleteBtnMouseClicked
        this.removeActiveRow();
    }//GEN-LAST:event_deleteBtnMouseClicked

    private void searchBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_searchBtnMouseClicked
        MachineSearchByDialog md = new MachineSearchByDialog(new JFrame(), true);
        md.setVisible(true);

        if (md.getDialogResult()) {

            final MachineSearchType searchType = md.getSearchType();
            final String value = md.getSearchValue();

            new SwingWorker<Object, Void>() {
                @Override
                protected Object doInBackground() {

                    try {
                        MachineRestService service = new MachineRestServiceImpl();

                        switch (searchType) {
                            case Code: {
                                return service.findByCode(value);
                            }
                            case Model: {
                                return service.findByModel(value);
                            }
                            default: {
                                return service.findByBrand(value);
                            }
                        }

                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                    }

                    return null;
                }

                @Override
                protected void done() {

                    Object data = null;
                    try {
                        data = this.get();
                        if (data == null) {
                            return;
                        }
                    } catch (InterruptedException ex) {
                        Logger.getLogger(MachinesManipulationPanel.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (ExecutionException ex) {
                        Logger.getLogger(MachinesManipulationPanel.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    if (searchType == MachineSearchType.Code) {

                        active.clear();
                        recomputeCanClick();
                        Utils.clearTable(machinesTable);
                        addRow((MachineDTO) data);

                    } else {
                        List<LinkedHashMap> machines = (List<LinkedHashMap>) data;
                        setToTable(machines);
                    }
                }
            }.execute();

        }
    }//GEN-LAST:event_searchBtnMouseClicked

    private void refreshBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_refreshBtnMouseClicked
        this.refresh();
    }//GEN-LAST:event_refreshBtnMouseClicked

    private void createBtnMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_createBtnMouseReleased
        this.createImpl();
    }//GEN-LAST:event_createBtnMouseReleased

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton createBtn;
    private javax.swing.JButton deleteBtn;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable machinesTable;
    private javax.swing.JButton refreshBtn;
    private javax.swing.JButton searchBtn;
    private javax.swing.JToolBar toolbar;
    private javax.swing.JButton updateBtn;
    // End of variables declaration//GEN-END:variables
    private JDialog addNewMachineDialog;
}
